package com.dex4d.ui.wallet.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.dex4d.BuildConfig;
import com.dex4d.R;
import com.dex4d.core.AppBaseFragment;
import com.dex4d.core.CustomApplication;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.ui.wallet.adapter.WalletTxAdapter;
import com.dex4d.ui.wallet.model.TxReceipt;
import com.dex4d.ui.wallet.model.WalletTx;
import com.framework.util.DisplayUtil;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;


public class WalletTxFragment extends AppBaseFragment implements SpringView.OnFreshListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;


    @BindView(R.id.tx_recycler)
    RecyclerView tx_recycler;

    @BindView(R.id.springview)
    SpringView springView;

    WalletTxAdapter txAdapter;

    public WalletTxFragment() {
        // Required empty public constructor
    }


    public static WalletTxFragment newInstance(String param1, String param2) {
        WalletTxFragment fragment = new WalletTxFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_wallet_tx;
    }

    @Override
    protected void initVariables() {
        springView.setHeader(new DefaultHeader(getActivity()));
        springView.setFooter(new DefaultFooter(getActivity()));

        springView.setListener(this);

        txAdapter = new WalletTxAdapter(getActivity());
        tx_recycler.setLayoutManager(new LinearLayoutManager(getActivity()));

        HorizontalDividerItemDecoration decoration =
                new HorizontalDividerItemDecoration
                        .Builder(getActivity())
                        .color(Color.TRANSPARENT)
                        .size(DisplayUtil.dip2px(getActivity(), 10))
                        .showLastDivider()
                        .build();
        tx_recycler.addItemDecoration(decoration);
        tx_recycler.setAdapter(txAdapter);
    }

    @Override
    protected void loadData() {
        tx(0);
    }

    private void tx(final int index) {

        Observable
                .create(new Observable.OnSubscribe<List<WalletTx>>() {
                    @Override
                    public void call(Subscriber<? super List<WalletTx>> subscriber) {//加载当前数据
                        List<WalletTx> list =
                                CustomApplication
                                        .getDb()
                                        .txDao()
                                        .getAll(index);

                        if (list == null || list.isEmpty()) {
                            subscriber.onCompleted();
                        } else {
                            subscriber.onNext(list);
                            subscriber.onCompleted();
                        }

                    }
                })
                .compose(new DefaultTransformer<List<WalletTx>>())
                .subscribe(new ProgressSubscriber<List<WalletTx>>(getActivity(), false) {
                    @Override
                    public void onNext(List<WalletTx> result) {
                        txAdapter.addAll(result, index);
                        springView.onFinishFreshAndLoad();
                        updateTx(result);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        springView.onFinishFreshAndLoad();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        springView.onFinishFreshAndLoad();
                    }
                });
    }

    /**
     * @param list
     */
    public void updateTx(List<WalletTx> list) {

        if (list == null || list.isEmpty()) return;

        List<String> hashes = new ArrayList<>();

        for (WalletTx tx : list) {//待确认交易
            if (tx.txReceiptStatus == 2) {
                hashes.add(tx.txHash);
            }
        }

        TxReceipt txReceipt = new TxReceipt(hashes);

        if (!hashes.isEmpty()) {
            //TODO 存在需要更新的数据状态
            //TODO 提交交易Hash,获取最新交易状态
            JsonApiWrapper
                    .serviceApi()
                    .gettxsinfo(BuildConfig.TX_URL_API + "/gettxsinfo", txReceipt)
                    .map(new Func1<TxReceipt, List<WalletTx>>() {
                        //TODO 把最新的交易状态更新到数据库
                        @Override
                        public List<WalletTx> call(TxReceipt txReceipt) {
                            //TODO 更新数据库
                            if (txReceipt != null
                                    && txReceipt.txstates != null
                                    && !txReceipt.txstates.isEmpty()) {
                                for (WalletTx tx : txReceipt.txstates) {
                                    CustomApplication.getDb().txDao()
                                            .updateTx(tx.txHash, tx.txReceiptStatus,
                                                    tx.blockHeight, tx.gasUsed);
                                }
                            }

                            return txReceipt.txstates;
                        }
                    })
                    .compose(new DefaultTransformer<List<WalletTx>>())
                    .subscribe(new ProgressSubscriber<List<WalletTx>>(getActivity(), false) {
                        @Override
                        public void onNext(List<WalletTx> result) {
                            txAdapter.updateAll(result);
                        }
                    });
        }
    }

    @Override
    public void onRefresh() {
        tx(0);
    }

    @Override
    public void onLoadmore() {
        tx(txAdapter.getItemCount());
    }

}
